import React, { useEffect, useRef, useState } from 'react';
import * as echarts from 'echarts';
import style from './styles.css';
import { BorderBox12,BorderBox13  } from '@jiaminghi/data-view-react';
import { ModuleTitle } from '../../style/globalStyledSet';

import { CenterPage, CenterBottom } from './style';



const DigitalApplication = ({ data }) => {
  const trendChartRef = useRef(null);
  const compareChartRef = useRef(null);
  const usageChartRef = useRef(null);
  const [highlightedDept, setHighlightedDept] = useState(null);

  useEffect(() => {
    if (!data) return;

    // 1. 当月工具使用情况
    const trendChart = echarts.init(trendChartRef.current);
    trendChart.setOption({
      title: {
        text: '各工具使用情况详细分布',
        textStyle: {  // 专用于标题文本样式的配置项
          color: '#bad9ed', // 修改为任意颜色值（如橙色）
          // fontSize: 18,     // 可选：调整字体大小
          // fontWeight: 'bold' // 可选：加粗
        },
        left: 'center'
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        },
        formatter: function (params) {
          let result = `${params[0].axisValue}<br/>`;
          let totalCount = 0;
          const tooltipItems = [];

          params.forEach(param => {
            if (param.value > 0) {
              const seriesName = param.seriesName.split('-');
              const toolName = seriesName[0];
              const detailName = seriesName[1];
              tooltipItems.push({
                detailName,
                value: param.value,
                color: param.color
              });
              totalCount += param.value;
            }
          });

          result += `总调用次数: ${totalCount}次<br/>`;
          result += '明细:<br/>';
          tooltipItems.forEach(item => {
            const percentage = ((item.value / totalCount) * 100).toFixed(1);
            result += `<span style="display:inline-block;width:10px;height:10px;background-color:${item.color};margin-right:5px;"></span>`;
            result += `${item.detailName}: ${item.value}次 (${percentage}%)<br/>`;
          });

          return result;
        }
      },
      legend: {
        show: false
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: data.digitalTools.categories,
        axisLabel: {
          color: '#bad9ed',
          interval: 0,
          rotate: 30
        }
      },
      yAxis: {
        axisLabel: {
          color: '#bad9ed',
        },
        type: 'value',
        name: '调用次数',
        nameTextStyle: {  // 名称文本样式配置
          color: '#bad9ed',      // 字体颜色（示例改为橙色）
        },
      },
      series: data.digitalTools.toolsDetailSeries
    });

    // 2. 事业部对比
    const compareChart = echarts.init(compareChartRef.current);
    compareChart.setOption({
      // title: {
      //   text: '各事业部数字化工具使用指数对比',
      //   textStyle: {  // 专用于标题文本样式的配置项
      //     color: '#bad9ed', // 修改为任意颜色值（如橙色）
      //     // fontSize: 18,     // 可选：调整字体大小
      //     // fontWeight: 'bold' // 可选：加粗
      //   },
      //   left: 'center'
      // },
      tooltip: {
        trigger: 'axis',
        formatter: function (params) {
          let result = `${params[0].axisValue}<br/>`;
          params.forEach(param => {
            result += `${param.seriesName}: ${param.value.toFixed(1)}分<br/>`;
          });
          return result;
        }
      },
      legend: {
        type: 'scroll',
        orient: 'horizontal',
        data: data.departments,
        textStyle: {  // 图例文本样式配置
          color: '#FFFFFF',          // 字体颜色（白色）
        },
        pageTextStyle: {  // 分页按钮文字样式
          color: '#CCCCCC'
        }
      },

      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: data.digitalTools.categories,
        axisLabel: {
          color: '#bad9ed',
          interval: 0,
          rotate: 30
        },
        axisLine: {
          lineStyle: {
            type: 'solid'
          }
        }
      },
      yAxis: {
        type: 'value',
        min: 30,
        max: 100,
        name: '使用指数',
        axisLabel: {
          color: '#bad9ed',
        },
        nameTextStyle: {  // 名称文本样式配置
          color: '#bad9ed',      // 字体颜色（示例改为橙色）
        },
      },
      series: data.digitalTools.byDepartmentSeries,
      color: [
        '#1890ff', '#13c2c2', '#52c41a', '#faad14',
        '#722ed1', '#eb2f96', '#fa541c', '#2f54eb', '#fa8c16'
      ]
    });

    // 3. 使用趋势
    const usageChart = echarts.init(usageChartRef.current);
    usageChart.setOption({
      // title: {
      //   text: '各事业部数字化工具使用趋势',
      //   textStyle: {  // 专用于标题文本样式的配置项
      //     color: '#bad9ed', // 修改为任意颜色值（如橙色）
      //     // fontSize: 18,     // 可选：调整字体大小
      //     // fontWeight: 'bold' // 可选：加粗
      //   },
      //   left: 'center'
      // },
      tooltip: {
        trigger: 'axis',
        formatter: function (params) {
          const month = params[0].axisValue;
          let result = `${month}<br/>`;

          if (highlightedDept) {
            const param = params.find(p => p.seriesName === highlightedDept);
            if (param) {
              const deptName = param.seriesName;
              const value = param.value;
              const monthIndex = data.months.indexOf(month);
              const deptData = data.digitalTools.trendData[deptName][monthIndex];

              result += `<b>${deptName}</b>: ${value.toFixed(1)}分<br/>`;
              result += '<div style="margin-left:10px;">';

              Object.entries(deptData.details).forEach(([toolName, details]) => {
                const toolAvg = details.reduce((sum, item) => sum + item.value, 0) / details.length;
                result += `${toolName}: ${toolAvg.toFixed(1)}分<br/>`;

                result += '<div style="margin-left:15px;font-size:12px;">';
                details.forEach(detail => {
                  result += `${detail.name}: ${detail.value.toFixed(1)}分<br/>`;
                });
                result += '</div>';
              });

              result += '</div>';
              return result;
            }
          }

          const hoverParam = params[0];
          const deptName = hoverParam.seriesName;
          const value = hoverParam.value;
          const monthIndex = data.months.indexOf(month);
          const deptData = data.digitalTools.trendData[deptName][monthIndex];

          result += `<b>${deptName}</b>: ${value.toFixed(1)}分<br/>`;
          result += '<div style="margin-left:10px;">';

          Object.entries(deptData.details).forEach(([toolName, details]) => {
            const toolAvg = details.reduce((sum, item) => sum + item.value, 0) / details.length;
            result += `${toolName}: ${toolAvg.toFixed(1)}分<br/>`;
          });

          result += '</div>';
          return result;
        }
      },
      legend: {
        type: 'scroll',
        orient: 'horizontal',
        data: data.departments,
        textStyle: {  // 图例文本样式配置
          color: '#FFFFFF',          // 字体颜色（白色）
        },
        pageTextStyle: {  // 分页按钮文字样式
          color: '#CCCCCC'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: data.months,
        axisLine: {
          lineStyle: {
            type: 'solid'
          }
        },
        axisLabel: {
          color: '#bad9ed',
        }
      },
      yAxis: {
        type: 'value',
        min: 30,
        max: 100,
        name: '工具指数',
        axisLabel: {
          color: '#bad9ed',
        },       
        nameTextStyle: {  // 名称文本样式配置
          color: '#bad9ed',      // 字体颜色（示例改为橙色）
        },
      },
      series: data.digitalTools.trendSeries,
      color: [
        '#1890ff', '#13c2c2', '#52c41a', '#faad14',
        '#722ed1', '#eb2f96', '#fa541c', '#2f54eb', '#fa8c16'
      ]
    });

    usageChart.on('highlight', function (params) {
      setHighlightedDept(params.batch?.[0]?.seriesName);
    });

    usageChart.on('downplay', function () {
      setHighlightedDept(null);
    });

    return () => {
      trendChart.dispose();
      compareChart.dispose();
      usageChart.dispose();
    };
  }, [data, highlightedDept]);

  return (
    // <CenterPage style={{ height: '90vh' }}>
    <CenterPage>
      <br />
      <ModuleTitle style={{ textAlign: 'left', width: '100%' }}>
        <i className='iconfont'>&#xe7f7;</i>
        <span>数字化应用</span>
      </ModuleTitle>

      {/* <BorderBox12 className={style["chart"]}> */}
      <BorderBox12 style={{ height:'3.625rem' }}>
        <br />
        <ModuleTitle>
          &nbsp;&nbsp;&nbsp;&nbsp;
          <span>数字化工具指数 - 当月</span>
        </ModuleTitle>
        <div ref={trendChartRef} className={style["chart"]} style={{ height:"3.125rem" }}  ></div>
      </BorderBox12>

      <BorderBox12 style={{ height:'3.5rem' }} >
        <br />
        <ModuleTitle>
          &nbsp;&nbsp;&nbsp;&nbsp;
          <span>数字化工具指数 - 事业部对比</span>
        </ModuleTitle>
        <br />
        <br />
        <div ref={compareChartRef} className={style["chart"]} style={{ height:'2.5rem' }}></div>
      </BorderBox12>

      <BorderBox12 style={{ height:'3.5rem' }}>
        <br />
        <ModuleTitle>
          &nbsp;&nbsp;&nbsp;&nbsp;
          <span>数字化工具指数 - 趋势</span>
        </ModuleTitle>
        <br /> 
        <br />
        <div ref={usageChartRef} className={style["chart"]} style={{ height:'2.5rem' }}></div>

      </BorderBox12>


    </CenterPage>
  );
};

export default DigitalApplication;